#include <unistd.h>
#include <fcntl.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <signal.h>

#include <errno.h>

#if (defined __linux)

#include <wiringPi.h>
#include <softPwm.h>

#endif

#define uchar unsigned char
 
#define LedPinRed    0
#define LedPinGreen  1
#define LedPinBlue   2

#define BufferSize 1024

#if (defined __linux)

void ledInit(void)
{
	softPwmCreate(LedPinRed,  0, 100);
	softPwmCreate(LedPinGreen,0, 100);
	softPwmCreate(LedPinBlue, 0, 100);
}
 
void ledColorSet(uchar r_val, uchar g_val, uchar b_val)
{
	softPwmWrite(LedPinRed,   r_val);
	softPwmWrite(LedPinGreen, g_val);
	softPwmWrite(LedPinBlue,  b_val);
}

#endif

int main(){

    #if (defined __linux)
	if(wiringPiSetup() == -1){
		printf("setup wiringPi failed !");
		return 1; 
	}
    #endif
    
    // 具名管道通信相关变量
    char readFifoName[] = "ledFifo";
    int readFd;
    if((readFd = open(readFifoName, O_RDONLY)) == -1){
        printf("Fail to open FIFO %s: %s", readFifoName, strerror(errno));
        exit(1);
    }

    char control[10];
    struct sigaction action;
    int status;
    int cnt = 0;

    char buffer[BufferSize];

    #if (defined __linux)
    ledInit();
    #endif

    while(1){
        memset(buffer,0,sizeof(buffer));
        int len = read(readFd, buffer, sizeof(buffer));
        if(strncmp("exit",buffer,5)==0) break;
        switch (buffer[0]){
            case 'r':
            case 'R':
                printf("%s", "Red led\n");
                #if (defined __linux)
                ledColorSet(0xff,0x00,0x00);
                #endif
                break;
            case 'g':
            case 'G':
                printf("%s", "Green led\n");
                #if (defined __linux)
		        ledColorSet(0x00,0xff,0x00);
                #endif
                break;
            case 'b':
            case 'B':
                printf("%s", "Blue led\n");
                #if (defined __linux)
		        ledColorSet(0x00,0x00,0xff); 
                #endif
                break;
            default:
                printf("%s", "None led\n");
                #if (defined __linux)
		        ledColorSet(0x00,0x00,0x00); 
                #endif
                break;
        }
        printf("%s", buffer);
    }
    return 0;
}